<template>
  <div class="pagination">
    <button @click="$emit('goPageNo', pageNo - 1)" :disabled="pageNo == 1">
      上一页
    </button>
    <button
      v-show="
        !(this.continues > this.totalPage) && pageNo > Math.ceil(continues / 2)
      "
      @click="$emit('goPageNo', 1)"
      :class="{ active: pageNo == 1 }"
    >
      1
    </button>
    <button v-show="pageNo > Math.ceil(continues / 2) + 1">···</button>
    <button
      v-for="(num, index) in startAndEnd.end"
      :key="index"
      v-show="num >= startAndEnd.start"
      @click="$emit('goPageNo', num)"
      :class="{ active: pageNo == num }"
    >
      {{ num }}
    </button>
    <button v-show="pageNo + Math.ceil(continues / 2) + 1 <= totalPage">
      ···
    </button>
    <button
      v-show="
        !(this.continues > this.totalPage) &&
        pageNo + Math.ceil(continues / 2) <= totalPage
      "
      @click="$emit('goPageNo', totalPage)"
      :class="{
        active: pageNo == totalPage,
      }"
    >
      {{ totalPage }}
    </button>
    <button
      @click="$emit('goPageNo', pageNo + 1)"
      :disabled="pageNo == totalPage"
    >
      下一页
    </button>
    <button>共{{ total }}条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["continues", "total", "pageSize", "pageNo"],
  computed: {
    totalPage() {
      return Math.ceil(this.total / this.pageSize);
    },
    //连续页的开始页和结束页
    startAndEnd() {
      let start = 0;
      let end = 0;
      //开始页=当前页数减分页器连续页的一半
      start = this.pageNo - parseInt(this.continues / 2);
      end = this.pageNo + parseInt(this.continues / 2);
      if (this.continues > this.totalPage) {
        //当总页数小于分页数
        console.log(this.continues > this.totalPage);
        (start = 1), (end = this.totalPage);
      } else {
        //开始页为负数,不正确
        if (start < 1) {
          start = 1;
          //当前页小，连续页也可以正常显示
          end = this.continues;
        }
        if (end > this.totalPage) {
          end = this.totalPage;
          //当前页大，连续页也可以正常显示
          start = this.totalPage - this.continues + 1;
        }
      }
      return { start, end };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>